var path = require('path')
var fs = require('fs')
var cfg = require('../config')
var OSS = require('ali-oss');
var redis = require("redis")
var axios = require('axios');
var redisclient = redis.createClient()


module.exports = {

  redis: redisclient,

  fsExistsSync(path) {
    try{
        fs.accessSync(path,fs.F_OK);
    }catch(e){
        return false;
    }
    return true;
  },

  mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
      return true;
    } else {
      if (this.mkdirsSync(path.dirname(dirname))) {
        fs.mkdirSync(dirname);
        return true;
      }
    }
  },

  redget(key) {
    return new Promise((resolve, reject) => {
      redisclient.get(key, (err, reply) => {
        if (err) resolve('error')
        resolve(reply)
      })
    })
  },

  redhget(key, field) {
    return new Promise((resolve, reject) => {
      redisclient.hget(key, field, (err, reply) => {
        if (err) resolve('error')
        resolve(reply)
      })
    })
  },

  getIP (req){
    let ip = req.headers['x-forwarded-for'] ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress;

    return ip.replace('::ffff:','')
  },

  download_image(url, image_path) {
    return axios({
      url: url,
      responseType: 'stream',
    }).then(response => {
      response.data.pipe(fs.createWriteStream(image_path));
      return {
        status: true,
        error: '',
      };
    }).catch(error => ({
      status: false,
      error: 'Error: ' + error.message,
    }))
  },
  move_image(sourceFilePath, targetFilePath) {
    this.mkdirsSync(path.dirname(targetFilePath))
    return new Promise((resolve, reject) => {
      fs.rename(sourceFilePath, targetFilePath, function (err) {
        if (err) {
          console.log(err)
          resolve('error');
        }
        resolve('ok')
        // fs.stat(targetFilePath, function (err, stats) {
        //   console.log(err)
        //   if (err) {
        //     resolve('error');
        //   }
        //   resolve(JSON.stringify(stats)) 
        // });
      })
    })
  },

  delete_imgage(image) {
    if (fs.existsSync(image)) {
      //从本地删除
      fs.unlink(image, function (error) {
        if (error) {
          console.log(error);
          return false;
        }
        return true;
      })
    }
  },

  //获取省份
  async get_china_area() {
    let getv = await this.redget('china_area');
    if (getv !== null) {
      return JSON.parse(getv)
    } else {
      let datas = await m_pub.AraeModel.get_list()
      let buildjson = []
      let find_children = (plist, item) => {
        let fresult = undefined
        for (let pitem of plist) {
          if (pitem.code == item.parent_code) {
            fresult = pitem
            break
          } else if (item.area_level > (pitem.level + 1)) {
            fresult = find_children(pitem.children, item)
            if (fresult !== undefined) {
              break
            }
            continue
          }
        }
        return fresult
      }
      for (let item of datas) {
        if (item.area_level == 1) {
          buildjson.push({ "code": item.area_code, "value": item.area_name, "label": item.area_name, "children": [], "level": item.area_level, "py": item.pinyin })
        } else { // if( item.area_level == 2)
          let r = find_children(buildjson, item)
          if (r !== undefined) {
            r.children.push({ "code": item.area_code, "value": item.area_name, "label": item.area_name, "children": [], "level": item.area_level, "py": item.pinyin })
          }
        }
        //else{ continue }
      }
      APP.comm.reds.set('china_area', JSON.stringify(buildjson));
      APP.comm.reds.expire('china_area', 3600)
      return buildjson
    }
  },
  async get_city_by_py(data) {
    let dd = await this.get_china_area()
    let province = [data.province, data.city, data.area]
    if (data.province && /^[A-Za-z]*$/.test(data.province)) {
      for (let f of dd) {
        if (f.py.startsWith(data.province)) {
          province[0] = f.label
          if (data.city && /^[A-Za-z]*$/.test(data.city)) {
            for (let city of f.children) {
              if (city.py.startsWith(data.city)) {
                province[1] = city.label
                province.push(city.children[0].label)
                break
              }
            }
          }
          break
        }
      }
    }
    // let province = [data.province, data.city]
    // if( data.province && /^[A-Za-z]*$/.test(data.province) ){
    //   let pname = await m_pub.AraeModel.find_pinyin(data.province)
    //   if( pname !== null ){
    //     province[0] = pname.area_name
    //   }
    // }

    // if( data.city && /^[A-Za-z]*$/.test(data.city) ){
    //   let pname = await m_pub.AraeModel.find_pinyin(data.city)
    //   if( pname !== null ){
    //     province[1] = pname.area_name
    //   }
    // }

    return province
  },

  oss: (() => {
    return new OSS({
      region: cfg.oss.region,
      accessKeyId: cfg.oss.accessKey,
      accessKeySecret: cfg.oss.accessKeySecret,
      bucket: cfg.oss.bucket
    });
  })()
}